package LawsonTransformJava.pgm;
import java.sql.*;
import java.util.Date;
import java.io.*;
import java.lang.reflect.InvocationTargetException;

import LawsonTransformJava.xref.CrossRef;
import LawsonTransformJava.xref.XrefDedCode;
// TODO Not used for previous client
//import LawsonTransformJava.xref.XrefDepartment;
//import LawsonTransformJava.xref.XrefJobCode;
import LawsonTransformJava.xref.XrefEmployee;
import LawsonTransformJava.xref.XrefProcessLevel;
import LawsonTransformJava.xref.XrefPaySumGrp;
import LawsonTransformJava.dao.DAOFactoryDB;
import LawsonTransformJava.dao.DAOPRTime;
import LawsonTransformJava.dao.DAObject;
import LawsonTransformJava.data.TblPRTime;
import LawsonTransformJava.main.ClassMain;

public class PR560RecType1 extends DAObject implements 
    DAOPRTime, Runnable {

	TblPRTime prt = new TblPRTime();

	private static XrefEmployee xEmployees = null;
	private static XrefProcessLevel xProcessLevels = null;
	private static XrefDedCode xDedCodes = null;
	private static XrefPaySumGrp xPaySumGrps = null;
	private int payrollYear = 0;
	private String prtDept = null;
	private boolean allowBlanks = false;
	private PRHistReport errReport = null;
	
    public PR560RecType1 (File output, File errOutput, File errReport, int payrollYear, boolean allowBlanks) throws SQLException {
    // initialization 
		try {
			this.output = new FileWriter(this.outputFile = output);
			this.errOutput = new FileWriter(this.errOutputFile = errOutput);
			this.errReport = new PRHistReport(errReport, new Date());
			this.payrollYear = payrollYear;

			//initialize
			init(allowBlanks);
		} catch (IOException e) {
			// Could no write properties file
			System.out.println("IOException: " + e);
		}
  }

  private void init(boolean allowBlanks) throws IOException, SQLException {
	// Set the data variables
	data = DAOFactoryDB.getDAODB(true);
	xEmployees = new XrefEmployee();
	xProcessLevels = new XrefProcessLevel(allowBlanks);
	xPaySumGrps = new XrefPaySumGrp(allowBlanks);
	xDedCodes = new XrefDedCode(allowBlanks);
	//Retain this value to be passed on to other Output files
	this.allowBlanks = allowBlanks;
	
	errReport.setPgmName("PR560");
	
	stmtData = data.getDataStatement();	    
	countStmtData = data.getCountStatement();
  }
  
  public TblPRTime findPRTime() {
		try {
			if (whereClause==null || whereClause.equals("")) {
				whereClause = " ";
//				whereClause = " WHERE " + TABLE_NAME + ".PAYROLL_YEAR=" + payrollYear;
			} else {
				whereClause = whereClause.trim();
//				whereClause = whereClause.trim() + " AND " + TABLE_NAME + ".PAYROLL_YEAR=" + payrollYear;
			}
			sqlData = "SELECT " + TABLE_NAME + ".* " + 
/*					TABLE_NAME + ".COMPANY, " +
					TABLE_NAME + ".PROCESS_LEVEL, " +
					TABLE_NAME + ".EMPLOYEE, " +
					TABLE_NAME + ".CHECK_ID, " +
					TABLE_NAME + ".PAY_SUM_GRP, " +
					TABLE_NAME + ".HOURS, " +
					TABLE_NAME + ".PER_END_DATE, " +
					TABLE_NAME + ".PAY_UNITS, " +
					TABLE_NAME + ".UNIT_MEASURE, " +
					TABLE_NAME + ".WAGE_AMOUNT, " +
					TABLE_NAME + ".NON_EARNINGS, " +
					TABLE_NAME + ".JOB_CODE, " +
					TABLE_NAME + ".WORK_STATE, " +
					TABLE_NAME + ".CHECK_AMT " +
*/					", " + TABLE_NAME2 + ".CHECK_NBR, " + TABLE_NAME2 + ".NET_PAY_AMT" +
					", " + TABLE_NAME2 + ".CHECK_DATE" +
					" FROM " + data.getSchema() + TABLE_NAME + 
					" LEFT JOIN " + data.getSchema() + TABLE_NAME2 +
					" ON " + TABLE_NAME + ".COMPANY = " + TABLE_NAME2 + ".COMPANY" +
					"    AND " + TABLE_NAME + ".CHECK_ID = " + TABLE_NAME2 + ".CHECK_ID" + 
					" " + (whereClause==null?"":whereClause) + 
					" ORDER BY " + TABLE_NAME + ".COMPANY, " + TABLE_NAME + ".EMPLOYEE, " + TABLE_NAME + ".CHECK_ID, " +
					"    " + TABLE_NAME + ".PAY_SUM_GRP";
			rslt = data.getDataStatement().executeQuery(sqlData);
			rsmd = rslt.getMetaData();
			if (rslt.next()){
				hasMoreRecs = true;
				prt = (TblPRTime) createObject(rslt, new TblPRTime());
			}
			else
				hasMoreRecs = false;
			return prt;
		} catch (SQLException e) {
		    // Could not connect to the database
			System.out.println("SQLException: " + e);
		} catch (InvocationTargetException ite) {
			System.out.println("InvocationException: " + ite);
		} catch (IllegalAccessException iae) {
			System.out.println("IllegalAccessException: " + iae);
		}
	  return null;
}

  public TblPRTime findPRTime(String employeeNumber) {
	try {
//		TblPRTime prt = new TblPRTime();
		
		if (whereClause==null) {
			whereClause = " WHERE EMPLOYEE=" + employeeNumber + " AND PAYROLL_YEAR=" + payrollYear;
		} else {
			whereClause = whereClause.trim() + " AND EMPLOYEE=" + employeeNumber + " AND PAYROLL_YEAR=" + payrollYear;
		}
		sqlData = "SELECT * FROM " + data.getSchema() + TABLE_NAME + " " + 
				(whereClause==null?"":whereClause);
		rslt = data.getDataStatement().executeQuery(sqlData);
		rsmd = rslt.getMetaData();
		rslt.next();
		prt = (TblPRTime) createObject(rslt, new TblPRTime());
		return prt;
	} catch (SQLException e) {
	    // Could not connect to the database
		System.out.println("SQLException: " + e);
	} catch (InvocationTargetException ite) {
		System.out.println("InvocationException: " + ite);
	} catch (IllegalAccessException iae) {
		System.out.println("IllegalAccessException: " + iae);
	}
	return new TblPRTime();
  }

  public TblPRTime nextPRTime() {
	  try {
		  if (rslt.next()){
			  hasMoreRecs = true;
			  prt = (TblPRTime) createObject(rslt, new TblPRTime());
		  }
		  else
			  hasMoreRecs = false;
		  return prt;
	  } catch (SQLException e) {
		  // Could not connect to the database
		  System.out.println("SQLException: " + e);
	  } catch (InvocationTargetException ite) {
		  System.out.println("InvocationException: " + ite);
	  } catch (IllegalAccessException iae) {
		  System.out.println("IllegalAccessException: " + iae);
	  }
	  return null;
  }

	public boolean hasMore () {
	  return hasMoreRecs;
	}

  public int countPRTime() {
	try {
		countRecs = data.getCountStatement().executeQuery("SELECT COUNT(*) " +
				"FROM " + data.getSchema() + "." + TABLE_NAME + 
					" LEFT JOIN " + data.getSchema() + TABLE_NAME2 +
					" ON " + TABLE_NAME + ".COMPANY = " + TABLE_NAME2 + ".COMPANY" +
					"    AND " + TABLE_NAME + ".CHECK_ID = " + TABLE_NAME2 + ".CHECK_ID " + 
				(whereClause==null?"":whereClause));
		countRecs.next();
		return recCount=countRecs.getInt(1);
		} catch (SQLException e) {
		    // Could not connect to the database
			System.out.println("SQLException: " + e);
		}
		return 0;
  }
  
  public void run()  {
//	  TblPRTime prt = null;
//	  TblPayDeductn pyd = null;
//	  TblPayMastr pym = null;
	  int prvCheckId = 0;
	  
	  try {
		//Clear out any old data in file
		output.write("");
		//Update current date/time
		System.out.println(errReport.getName() + " Start  " + Report.getDateFormat().format(new Date()));
			
		prt = findPRTime();
		//Setup counters for the Report
		errReport.initCounter("PRT Records " + this.whereClause.trim(), countPRTime());
		errReport.initCounter("PRT Records in Error", 0);
		errReport.initCounter("PRT Records Written", 0);
		errReport.initCounter("PYD Records in Error", 0);
		errReport.initCounter("PYD Records Written", 0);
		errReport.initCounter("PYM Records in Error", 0);
		errReport.initCounter("PYM Records Written", 0);
//		errReport.addToCounter("PYD Records", countPayDeductn());
//		errReport.addToCounter("PYM Records", countPayMastr());
		prvCheckId=prt.getCheck_id();
		prtDept=prt.getDepartment();
		//Pass the PRT Department into the other record types for PL translation
		PR560RecType2 pr560Rec2 = new PR560RecType2(this.output, this.errOutput, this.errReport, this.allowBlanks);
//		PR560RecType3 pr560Rec3 = new PR560RecType3(this.output, this.errOutput, this.errReport, this.allowBlanks);
		while (hasMore()) {
			if (prvCheckId!=prt.getCheck_id()) {
				errReport.addToCounter("PRT Unique Records", 1);
				output.flush();
				pr560Rec2.setCheckId(prvCheckId);
				pr560Rec2.setDepartment(prtDept);
				pr560Rec2.run();
//				pr560Rec3.setCheckId(prvCheckId);
//				pr560Rec3.run();
				prvCheckId=prt.getCheck_id();
				prtDept=prt.getDepartment();
			}
//			output.append(writePR560Layout(prt) + "\n");
			writePR560Layout(prt);
			prt = nextPRTime();
		}
		errReport.addToCounter("PRT Unique Records", 1);
		output.flush();
		pr560Rec2.setCheckId(prvCheckId);
		pr560Rec2.setDepartment(prtDept);
		pr560Rec2.run();
//		pr560Rec3.setCheckId(prvCheckId);
//		pr560Rec3.run();
		//Update current date/time
		System.out.println(errReport.getName() + " Finish " + Report.getDateFormat().format(new Date()));

		//Write Record Counts
		errReport.writeRecordCounts();
		
		//Reclaim Resources
		fileCleanup();

	} catch (IOException e) {
		// Could not write properties file
		// Could not create output file
		System.out.println("IOException: " + e);
	} catch (SQLException e) {
		// Could not connect to the database
		System.out.println("SQLException: " + e);
		System.exit(1);
	}
  }
  
	//Output the PR560 format - Record Type 1
//	public String writePR560Layout(TblPRTime prt) {
	public void writePR560Layout(TblPRTime prt) throws IOException {

		String writeValue = null;
		
		writeValue =
				"1" + "," +
				ClassMain.COMPANY + "," +
//				prt.getEmployee() + "," +
				xEmployees.xlate(Integer.toString(prt.getEmployee())) + "," + 
				"\"" + xProcessLevels.xlate(prt.getProcess_level() + (prt.getDepartment().equals("")?prtDept:prt.getDepartment())) + "\"" + "," +//Process Level
//				prt.getProcess_level() + "," +						//Process Level
//				prt.getProcess_level() + "," +
//				"\"" + xDepartments.xlate(prt.getProcess_level() + prt.getDepartment()) + "\"," +		//Department
//				prt.getDepartment() + "," +							//Department
				"," +												//Department
				prt.getCheck_id() + "," +
				"\"" + xPaySumGrps.xlate(prt.getPay_sum_grp()) + "\"" + "," +		//PaySumGrp
//				prt.getPay_sum_grp() + "," +						//PaySumGrp
				"," +
				prt.getPer_end_date() + "," +			//Tr_date
				prt.getCheck_date() + "," +				//Check_date
				prt.getHours() + "," +
				prt.getPay_units() + "," +
				prt.getUnit_measure() + "," +
				prt.getWage_amount() + "," +
				prt.getNon_earnings() + "," +
				"," +
				"," +
				"," +
//				xJobCodes.xlate(prt.getJob_code()) + "," +			//JobCode
//				prt.getJob_code() + "," +							//JobCode
				"," +												//JobCode - Blanks
				prt.getWork_state() + "," +
				"," +
				prt.getCheck_Nbr() + "," +
				"," +
				"," +
				"," +
				(prt.getDist_Amount()==0.0?prt.getCheck_Amt():"") + "," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				"," +
				","
			;
		
		if (CrossRef.isError()) {
			//Increment Record in Error
			errReport.addToCounter("PRT Records in Error", 1);
			//Write to Error File
			this.errOutput.append(writeValue + "\n");
			this.errOutput.flush();
			CrossRef.resetError();
		}
		else {
			//Increment Record Written
			errReport.addToCounter("PRT Records Written", 1);
			//Write to Load File
			this.output.append(writeValue + "\n");
			this.output.flush();
		}
	}
	
	
	public static XrefEmployee getXrefEmployees() {
		return xEmployees;
	}
	
	public static XrefProcessLevel getXrefProcessLevels() {
		return xProcessLevels;
	}
	
	public static XrefDedCode getXrefDedCodes() {
		return xDedCodes;
	}
	
//	public static XrefDepartment getXrefDepartments() {
//		return xDepartments;
//	}
	
	public FileWriter getOutput() {
		return this.output;
	}
	
	public void fileCleanup() throws IOException {
		errReport.flush();
		errReport.close();
		output.flush();
		output.close();
		errOutput.flush();
		errOutput.close();
	}
}